<?php 
namespace app\admin\controller;
use think\Controller;
use catetree\Catetree;

class Goods extends Controller{

	public function index(){

		$join=[
			['brand b','g.brand_id = b.id','LEFT'],
			['type t','g.type_id = t.id','LEFT'],
		];

		$goodsRes = db('goods')->alias('g')
					->field('g.*,b.brand_name,t.type_name')
					->join($join)
					->order('g.id desc')
					->paginate(15);
		$this->assign([
			'goodsRes'	=>$goodsRes,
		]);
		return view();
	}

	public function add(){
		// 获取商品分类
		$cate=new Catetree();
		$goods_res=db('category')->select();
		$goodsCateRes=$cate->catetree($goods_res);

		// 获取品牌
		$brand = db('brand')->field('id,brand_name')->select();

		// 获取会员等级
		$memberLevel = db('member_level')->select();

		// 获取商品类型
		$goods_type = db('type')->select();

		$this->assign([
			'goodsCateRes'	=>$goodsCateRes,
			'brand'			=>$brand,
			'memberLevel'	=>$memberLevel,
			'goods_type'	=>$goods_type,
		]);

		if(request()->isPost()){
			$data = input('post.');
			$dataRes = model('goods')->save($data);
			if($dataRes){
				$this->success('商品添加成功！',url('goods/index'));
			}else{
				$this->error('商品添加失败！');
			}
		}
		return view();
	}

	public function edit($id){
		// 获取商品分类
		$cate=new Catetree();
		$goods_res=db('category')->select();
		$goodsCateRes=$cate->catetree($goods_res);

		// 获取品牌
		$brand = db('brand')->field('id,brand_name')->select();

		// 获取会员等级
		$memberLevel = db('member_level')->select();

		// 获取商品类型
		$goods_type = db('type')->select();

		// 获取商品属性
		$goods = db('goods')->find($id);

		// 获取商品会员价格
		$mpRes = db('member_price')->where(['goods_id'=>$id])->select();

		$this->assign([
			'goodsCateRes'	=>$goodsCateRes,
			'brand'			=>$brand,
			'memberLevel'	=>$memberLevel,
			'goods_type'	=>$goods_type,
			'goods'			=>$goods,
			'mpRes'			=>$mpRes,
		]);



		return view();
	}

	public function del($id){
		$res = model('goods')->destroy($id);
		if($res){
			$this->success('商品删除成功',url('admin/Goods/index'));
		}else{
			$this->error('商品删除失败');
		}	
	}

	public function upload(){
		$file=request()->file('brand_image');
		if($file){
			$info=$file->move(ROOT_PATH.'public'.DS.'static'.DS.'upload');
			if($info){
				return $info->getSaveName();
			}else{
				echo $file->getError();
				die;
			}
		}
	}

}